//! # 分布式追踪处理器模块
//! 
//! 提供分布式追踪的具体实现，支持span管理、事件记录和数据导出。
//! 集成常见的追踪后端，如Jaeger、Zipkin等。

use super::traits::TracingProcessor;
use super::context::ObservabilityContext;
use rustcloud_core::{ServiceResult, ServiceError};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use async_trait::async_trait;

/// 内存追踪处理器
/// 
/// 将追踪数据存储在内存中，主要用于测试和开发环境。
pub struct MemoryTracingProcessor {
    /// 处理器名称
    name: String,
    
    /// 是否启用
    enabled: bool,
    
    /// 存储的spans
    spans: Arc<RwLock<Vec<TracingSpan>>>,
    
    /// 存储的事件
    events: Arc<RwLock<Vec<TracingEvent>>>,
    
    /// 配置
    config: TracingProcessorConfig,
}

/// 追踪span数据结构
#[derive(Debug, Clone)]
pub struct TracingSpan {
    /// 追踪ID
    pub trace_id: String,
    
    /// Span ID
    pub span_id: String,
    
    /// 父Span ID
    pub parent_span_id: Option<String>,
    
    /// 服务名称
    pub service_name: String,
    
    /// 操作名称
    pub operation_name: String,
    
    /// 开始时间戳（微秒）
    pub start_time_us: u64,
    
    /// 结束时间戳（微秒）
    pub end_time_us: Option<u64>,
    
    /// 标签
    pub tags: HashMap<String, String>,
    
    /// 日志
    pub logs: Vec<TracingLog>,
    
    /// 状态
    pub status: SpanStatus,
}

/// 追踪事件数据结构
#[derive(Debug, Clone)]
pub struct TracingEvent {
    /// 追踪ID
    pub trace_id: String,
    
    /// Span ID
    pub span_id: String,
    
    /// 事件名称
    pub name: String,
    
    /// 时间戳（微秒）
    pub timestamp_us: u64,
    
    /// 属性
    pub attributes: HashMap<String, serde_json::Value>,
}

/// 追踪日志
#[derive(Debug, Clone)]
pub struct TracingLog {
    /// 时间戳（微秒）
    pub timestamp_us: u64,
    
    /// 字段
    pub fields: HashMap<String, serde_json::Value>,
}

/// Span状态
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpanStatus {
    /// 未设置
    Unset,
    /// 成功
    Ok,
    /// 错误
    Error(String),
}

/// 追踪处理器配置
#[derive(Debug, Clone)]
pub struct TracingProcessorConfig {
    /// 最大存储的span数量
    pub max_spans: usize,
    
    /// 最大存储的事件数量
    pub max_events: usize,
    
    /// 自动导出间隔（毫秒）
    pub export_interval_ms: u64,
    
    /// 批处理大小
    pub batch_size: usize,
}

impl Default for TracingProcessorConfig {
    fn default() -> Self {
        Self {
            max_spans: 10000,
            max_events: 50000,
            export_interval_ms: 5000,
            batch_size: 100,
        }
    }
}

impl MemoryTracingProcessor {
    /// 创建新的内存追踪处理器
    /// 
    /// # 参数
    /// * `name` - 处理器名称
    /// * `config` - 处理器配置
    /// 
    /// # 返回值
    /// 新的内存追踪处理器实例
    pub fn new(name: String, config: TracingProcessorConfig) -> Self {
        Self {
            name,
            enabled: true,
            spans: Arc::new(RwLock::new(Vec::new())),
            events: Arc::new(RwLock::new(Vec::new())),
            config,
        }
    }

    /// 获取所有spans
    /// 
    /// # 返回值
    /// 所有存储的spans的副本
    pub async fn get_spans(&self) -> Vec<TracingSpan> {
        self.spans.read().await.clone()
    }

    /// 获取所有事件
    /// 
    /// # 返回值
    /// 所有存储的事件的副本
    pub async fn get_events(&self) -> Vec<TracingEvent> {
        self.events.read().await.clone()
    }

    /// 根据追踪ID获取spans
    /// 
    /// # 参数
    /// * `trace_id` - 追踪ID
    /// 
    /// # 返回值
    /// 指定追踪ID的所有spans
    pub async fn get_spans_by_trace_id(&self, trace_id: &str) -> Vec<TracingSpan> {
        let spans = self.spans.read().await;
        spans.iter()
            .filter(|span| span.trace_id == trace_id)
            .cloned()
            .collect()
    }

    /// 清空所有数据
    pub async fn clear(&self) {
        let mut spans = self.spans.write().await;
        let mut events = self.events.write().await;
        spans.clear();
        events.clear();
    }

    /// 设置启用状态
    /// 
    /// # 参数
    /// * `enabled` - 是否启用
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// 获取统计信息
    /// 
    /// # 返回值
    /// 处理器统计信息
    pub async fn get_stats(&self) -> TracingProcessorStats {
        let spans = self.spans.read().await;
        let events = self.events.read().await;
        
        TracingProcessorStats {
            total_spans: spans.len(),
            total_events: events.len(),
            active_spans: spans.iter().filter(|s| s.end_time_us.is_none()).count(),
            completed_spans: spans.iter().filter(|s| s.end_time_us.is_some()).count(),
        }
    }

    /// 维护存储大小限制
    async fn maintain_storage_limits(&self) {
        // 限制spans数量
        {
            let mut spans = self.spans.write().await;
            if spans.len() > self.config.max_spans {
                let excess = spans.len() - self.config.max_spans;
                spans.drain(0..excess);
                tracing::debug!("清理了 {} 个旧的spans", excess);
            }
        }

        // 限制事件数量
        {
            let mut events = self.events.write().await;
            if events.len() > self.config.max_events {
                let excess = events.len() - self.config.max_events;
                events.drain(0..excess);
                tracing::debug!("清理了 {} 个旧的事件", excess);
            }
        }
    }
}

#[async_trait]
impl TracingProcessor for MemoryTracingProcessor {
    async fn start_span(&self, context: &ObservabilityContext) -> ServiceResult<()> {
        if !self.enabled {
            return Ok(());
        }

        let span = TracingSpan {
            trace_id: context.trace_id.clone(),
            span_id: context.span_id.clone(),
            parent_span_id: context.parent_span_id.clone(),
            service_name: context.service_name.clone(),
            operation_name: context.operation_name.clone(),
            start_time_us: context.start_time.elapsed().as_micros() as u64,
            end_time_us: None,
            tags: context.labels.clone(),
            logs: Vec::new(),
            status: SpanStatus::Unset,
        };

        {
            let mut spans = self.spans.write().await;
            spans.push(span);
        }

        // 维护存储限制
        self.maintain_storage_limits().await;

        tracing::trace!("开始span: {} ({})", context.operation_name, context.span_id);
        Ok(())
    }

    async fn end_span(&self, context: &ObservabilityContext) -> ServiceResult<()> {
        if !self.enabled {
            return Ok(());
        }

        let mut spans = self.spans.write().await;
        if let Some(span) = spans.iter_mut().find(|s| s.span_id == context.span_id) {
            span.end_time_us = Some(context.start_time.elapsed().as_micros() as u64);
            
            // 根据上下文状态设置span状态
            span.status = match &context.state {
                super::context::ContextState::Completed => SpanStatus::Ok,
                super::context::ContextState::Error(error) => SpanStatus::Error(error.clone()),
                _ => SpanStatus::Unset,
            };
            
            tracing::trace!("结束span: {} ({})", context.operation_name, context.span_id);
        }

        Ok(())
    }

    async fn add_event(&self, context: &ObservabilityContext, name: &str, attributes: HashMap<String, serde_json::Value>) -> ServiceResult<()> {
        if !self.enabled {
            return Ok(());
        }

        let event = TracingEvent {
            trace_id: context.trace_id.clone(),
            span_id: context.span_id.clone(),
            name: name.to_string(),
            timestamp_us: context.start_time.elapsed().as_micros() as u64,
            attributes,
        };

        {
            let mut events = self.events.write().await;
            events.push(event);
        }

        // 维护存储限制
        self.maintain_storage_limits().await;

        tracing::trace!("添加事件: {} 到span {}", name, context.span_id);
        Ok(())
    }

    async fn export(&self) -> ServiceResult<()> {
        if !self.enabled {
            return Ok(());
        }

        let spans_count = self.spans.read().await.len();
        let events_count = self.events.read().await.len();
        
        tracing::debug!("导出追踪数据: {} spans, {} events", spans_count, events_count);
        
        // 在实际实现中，这里会将数据发送到外部系统
        // 比如Jaeger、Zipkin等
        
        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }
}

/// 追踪处理器统计信息
#[derive(Debug, Clone)]
pub struct TracingProcessorStats {
    /// 总span数量
    pub total_spans: usize,
    
    /// 总事件数量
    pub total_events: usize,
    
    /// 活跃span数量
    pub active_spans: usize,
    
    /// 已完成span数量
    pub completed_spans: usize,
}

/// NoOp追踪处理器
/// 
/// 不执行任何操作的追踪处理器，用于禁用追踪功能。
pub struct NoOpTracingProcessor {
    name: String,
}

impl NoOpTracingProcessor {
    /// 创建新的NoOp追踪处理器
    /// 
    /// # 返回值
    /// 新的NoOp追踪处理器实例
    pub fn new() -> Self {
        Self {
            name: "noop".to_string(),
        }
    }
}

impl Default for NoOpTracingProcessor {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl TracingProcessor for NoOpTracingProcessor {
    async fn start_span(&self, _context: &ObservabilityContext) -> ServiceResult<()> {
        Ok(())
    }

    async fn end_span(&self, _context: &ObservabilityContext) -> ServiceResult<()> {
        Ok(())
    }

    async fn add_event(&self, _context: &ObservabilityContext, _name: &str, _attributes: HashMap<String, serde_json::Value>) -> ServiceResult<()> {
        Ok(())
    }

    async fn export(&self) -> ServiceResult<()> {
        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn is_enabled(&self) -> bool {
        false
    }
}

/// 组合追踪处理器
/// 
/// 可以同时使用多个追踪处理器，将数据发送到多个后端。
pub struct CompositeTracingProcessor {
    name: String,
    processors: Vec<Arc<dyn TracingProcessor>>,
}

impl CompositeTracingProcessor {
    /// 创建新的组合追踪处理器
    /// 
    /// # 参数
    /// * `name` - 处理器名称
    /// * `processors` - 子处理器列表
    /// 
    /// # 返回值
    /// 新的组合追踪处理器实例
    pub fn new(name: String, processors: Vec<Arc<dyn TracingProcessor>>) -> Self {
        Self {
            name,
            processors,
        }
    }

    /// 添加处理器
    /// 
    /// # 参数
    /// * `processor` - 要添加的处理器
    pub fn add_processor(&mut self, processor: Arc<dyn TracingProcessor>) {
        self.processors.push(processor);
    }

    /// 获取处理器数量
    /// 
    /// # 返回值
    /// 子处理器的数量
    pub fn processor_count(&self) -> usize {
        self.processors.len()
    }
}

#[async_trait]
impl TracingProcessor for CompositeTracingProcessor {
    async fn start_span(&self, context: &ObservabilityContext) -> ServiceResult<()> {
        for processor in &self.processors {
            if let Err(e) = processor.start_span(context).await {
                tracing::error!("追踪处理器 {} 启动span失败: {}", processor.name(), e);
            }
        }
        Ok(())
    }

    async fn end_span(&self, context: &ObservabilityContext) -> ServiceResult<()> {
        for processor in &self.processors {
            if let Err(e) = processor.end_span(context).await {
                tracing::error!("追踪处理器 {} 结束span失败: {}", processor.name(), e);
            }
        }
        Ok(())
    }

    async fn add_event(&self, context: &ObservabilityContext, name: &str, attributes: HashMap<String, serde_json::Value>) -> ServiceResult<()> {
        for processor in &self.processors {
            if let Err(e) = processor.add_event(context, name, attributes.clone()).await {
                tracing::error!("追踪处理器 {} 添加事件失败: {}", processor.name(), e);
            }
        }
        Ok(())
    }

    async fn export(&self) -> ServiceResult<()> {
        for processor in &self.processors {
            if let Err(e) = processor.export().await {
                tracing::error!("追踪处理器 {} 导出失败: {}", processor.name(), e);
            }
        }
        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn is_enabled(&self) -> bool {
        self.processors.iter().any(|p| p.is_enabled())
    }
}